package com.hskn.hss.core.aspectj;

import com.hskn.hss.core.annotation.DataScope;
import com.hskn.hss.core.domain.BaseEntity;
import com.hskn.hss.core.utils.LoginUtils;
import com.hskn.hss.core.utils.StringUtils;
import com.hskn.hss.core.utils.spring.SpringUtils;
import com.hskn.hss.module.depart.entity.SysDepart;
import com.hskn.hss.module.depart.service.impl.SysDepartServiceImpl;
import com.hskn.hss.module.role.entity.SysRole;
import com.hskn.hss.module.user.entity.User;
import com.hskn.hss.module.user.service.impl.UserServiceImpl;
import com.hskn.hss.module.userdepart.service.impl.SysUserDepartServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.List;

/**
 * 数据过滤处理
 *
 * @author ruoyi
 */
@Aspect
@Component
public class DataScopeAspect {
    /**
     * 全部数据权限
     */
    public static final String DATA_SCOPE_ALL = "5";

    /**
     * 自定数据权限
     */
    public static final String DATA_SCOPE_CUSTOM = "4";

    /**
     * 部门数据权限
     */
    public static final String DATA_SCOPE_DEPT = "2";

    /**
     * 部门及以下数据权限
     */
    public static final String DATA_SCOPE_DEPT_AND_CHILD = "3";

    /**
     * 仅本人数据权限
     */
    public static final String DATA_SCOPE_SELF = "1";

    /**
     * 数据权限过滤关键字
     */
    public static final String DATA_SCOPE = "dataScope";

    /**
     * 数据范围过滤
     *
     * @param joinPoint 切点
     * @param user      用户
     * @param deptIds   部门集合
     * @param userAlias 用户权限ID串
     * @param depAlias 部门权限ID串
     */
    public static void dataScopeFilter(JoinPoint joinPoint, User user, List<String> deptIds,String userAlias , String depAlias) {
        StringBuilder sqlString = new StringBuilder();
        for (SysRole role : user.getRoles()) {
            String dataScope = role.getDataScope();
             if (DATA_SCOPE_ALL.equals(dataScope)) {
                sqlString = new StringBuilder();
                break;
            } else if (DATA_SCOPE_CUSTOM.equals(dataScope)) {
                 if (StringUtils.isNotEmpty(depAlias)) {
                     sqlString.append(StringUtils.format(
                             " OR {} IN ( SELECT dep_values FROM sys_permission_role WHERE role_id = {} ) ",depAlias,
                             "'"+role.getId()+"'"));
                 }
             } else if (DATA_SCOPE_DEPT.equals(dataScope)) {
                 if (StringUtils.isNotEmpty(depAlias)) {
                     for (String depId:depAlias.split(",")) {
                         sqlString.append(StringUtils.format(" OR {} IN ({})", depId , "'"+user.getDepid()+"'"));
                     }
                 }
             } else if (DATA_SCOPE_DEPT_AND_CHILD.equals(dataScope)) {
                 if (CollectionUtils.isNotEmpty(deptIds)) {
                     String str="";
                     for (String depId:deptIds) {
                         str+="'"+depId+"'"+",";
                     }
                     sqlString.append(StringUtils.format(
                             " OR {} IN ( {})",depAlias,
                             str.substring(0,str.lastIndexOf(","))));
                 }

             } else if (DATA_SCOPE_SELF.equals(dataScope)) {
                if (StringUtils.isNotBlank(userAlias)) {
                    for (String u:userAlias.split(",")) {
                        sqlString.append(StringUtils.format(" OR {} = {} ", u, "'"+user.getUid()+"'"));
                    }
                } else {
                    // 数据权限为仅本人且没有userAlias别名不查询任何数据
                    sqlString.append(" OR 1=0 ");
                }
            }
        }
        if (StringUtils.isNotBlank(sqlString.toString())) {
            Object params = joinPoint.getArgs()[0];
            if (StringUtils.isNotNull(params) && params instanceof BaseEntity) {
                BaseEntity baseEntity = (BaseEntity) params;
                baseEntity.getParams().put(DATA_SCOPE, " (" + sqlString.substring(4) + ")");
            }
        }
    }

    // 配置织入点
    @Pointcut("@annotation(com.hskn.hss.core.annotation.DataScope)")
    public void dataScopePointCut() {
    }

    @Before("dataScopePointCut()")
    public void doBefore(JoinPoint point) throws Throwable {
        clearDataScope(point);
        handleDataScope(point);
    }

    protected void handleDataScope(final JoinPoint joinPoint) {
        // 获得注解
        DataScope controllerDataScope = getAnnotationLog(joinPoint);
        if (controllerDataScope == null) {
            return;
        }
        // 获取当前的用户
        User loginUser = LoginUtils.getUser();
        loginUser = SpringUtils.getBean(UserServiceImpl.class).getUserDetail(loginUser.getUid());
        List<SysRole> roleList = LoginUtils.getLoginRoleList(loginUser);
        loginUser.setRoles(roleList);
        loginUser.setDepid(SpringUtils.getBean(SysUserDepartServiceImpl.class).getDeptidByUid(loginUser.getUid()));
        List<String> depIds = SpringUtils.getBean(SysDepartServiceImpl.class).getChildIdsByIId(loginUser.getDepid());
        if (StringUtils.isNotNull(loginUser)) {
            // 如果是超级管理员，则不过滤数据
            if (!loginUser.isAdmin()) {
                dataScopeFilter(joinPoint, loginUser,depIds, controllerDataScope.userAlias(), controllerDataScope.deptAlias());
            }
         }
    }



    /**
     * 是否存在注解，如果存在就获取
     */
    private DataScope getAnnotationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null) {
            return method.getAnnotation(DataScope.class);
        }
        return null;
    }

    /**
     * 拼接权限sql前先清空params.dataScope参数防止注入
     */
    private void clearDataScope(final JoinPoint joinPoint) {
        Object params = joinPoint.getArgs()[0];
        if (StringUtils.isNotNull(params) && params instanceof BaseEntity) {
            BaseEntity baseEntity = (BaseEntity) params;
            baseEntity.getParams().put(DATA_SCOPE, "");
        }
    }
}
